package com.alphas.openapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alphas.openapiclientsdk.model.User;

import java.util.HashMap;
import java.util.Map;

import static com.alphas.openapiclientsdk.utils.SignUtils.genSign;

public class ApiClient {
    final static String GATEWAY_HOST = "http://localhost:8090";
    private String accessKey;
    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name){
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("name",name);
        String string = HttpUtil.get(GATEWAY_HOST + "/api/name", stringObjectHashMap);
        return string;
    }
    public String getNameByPost(String name){
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("name",name);
        String string = HttpUtil.post(GATEWAY_HOST + "/api/name", stringObjectHashMap);
        return string;
    }
    public Map<String,String> getHeaderMap(String body){
        Map<String,String> map = new HashMap<>();
        map.put("accessKey",accessKey);
//        不能将secretKey直接发送
//        map.put("secretKey",secretKey);
        map.put("body",body);
        map.put("timestamp",String.valueOf(System
                .currentTimeMillis()/1000));
        map.put("nonce", RandomUtil.randomNumbers(3));
        map.put("sign",genSign(body,secretKey));
        return map;
    }
    public String getNameByPostUser(User user){
        String jsonStr = JSONUtil.toJsonStr(user);
//        System.out.println("这是客户端的body" + jsonStr);
        HttpResponse execute = HttpRequest.post(GATEWAY_HOST + "/api/name/user").body(jsonStr)
                .addHeaders(getHeaderMap(jsonStr)).execute();
        int status = execute.getStatus();
        System.out.println(status);
        return execute.body();
    }

}
